<template>
	<a-drawer
		:title="formData.id ? '编辑试剂' : '增加试剂'"
		:width="1200"
		:visible="visible"
		:destroy-on-close="true"
		:footer-style="{ textAlign: 'right' }"
		@close="onClose"
		:mask-closable="false"
	>
		<a-form ref="formRef" :model="formData" layout="vertical">
			<a-tabs v-model:activeKey="activeKey">
				<a-tab-pane key="base" tab="基本信息">
					<a-row :gutter="24">

						<a-col :span="12">
							<a-form-item label="识别方式：">
								<a-row>
									<a-col :span="8">RFID：
										<a-switch v-model:checked="rfidFlag" checked-children="有"
												  un-checked-children="无"/>
									</a-col>
									<a-col :span="8">二维码：
										<a-switch v-model:checked="qrcodeFlag" checked-children="有"
												  un-checked-children="无"/>
									</a-col>
									<a-col :span="8">条形码：
										<a-switch v-model:checked="barcodeFlag" checked-children="有"
												  un-checked-children="无"/>
									</a-col>
								</a-row>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="RFID：" name="rfidNum" v-if="rfidFlag"
										 :rules="[{ required: rfidFlag, message: '请输入RFID' }]">
								<a-input v-model:value.trim="formData.rfidNum" placeholder="请输入RFID" allow-clear/>
							</a-form-item>
						</a-col>

						<a-col :span="8">
							<a-form-item label="初始净量：" name="reagentInitNetAmount"
										 :rules="[{ required: true, message: '请输入初始净量' }]">
								<a-input-number precision="2" v-model:value="formData.reagentInitNetAmount"
												placeholder="请输入初始净量" allow-clear :disabled="!addFlag">
									<template #addonAfter>
										<a-select v-model:value="formData.reagentUnit" style="width: 80px" :disabled="!addFlag">
											<a-select-option value="0">毫升</a-select-option>
											<a-select-option value="1">克</a-select-option>
										</a-select>
									</template>
								</a-input-number>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="有效期：" name="reagentValidityPeriod">
								<a-date-picker v-model:value="formData.reagentValidityPeriod" value-format="YYYY-MM-DD" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="容器重量(g)：" name="reagentContainerWeight">
								<a-input v-model:value.trim="formData.reagentContainerWeight" :disabled="true"/>
							</a-form-item>
						</a-col>

						<a-col :span="8">
							<a-form-item label="名称：" name="goodsName">
								<a-input v-model:value.trim="formData.goodsName" :disabled="true"/>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="CAS：" name="reagentCasNo">
								<a-input v-model:value.trim="formData.reagentCasNo" :disabled="true"/>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="形态：" name="reagentFormId"
										 :rules="[{ required: true, message: '请选择形态' }]">
								<a-select v-model:value="formData.reagentFormId" placeholder="请选择试剂形态"
										  :options="formTypeOptions" allowClear :disabled="!addFlag"/>
							</a-form-item>
						</a-col>

						<a-col :span="8">
							<a-form-item label="类型：" name="reagentClassId"
										 :rules="[{ required: true, message: '请选择类型' }]">
								<a-select v-model:value="formData.reagentClassId" placeholder="请选择试剂类型"
										  :options="storageTypeOptions" allowClear :disabled="!addFlag"/>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="密度(g/ml)：" name="reagentDensity"
										 :rules="[{ required: true, message: '请输入密度' }]">
								<a-input-number precision="2" v-model:value="formData.reagentDensity"
												placeholder="请输入试剂密度" allow-clear addon-after="g/ml"
												style="width: 100%" :disabled="!addFlag"/>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="试剂瓶类型：" name="reagentBottleType"
										 :rules="[{ required: true, message: '请选择试剂瓶类型' }]">
								<a-select v-model:value="formData.reagentBottleType" placeholder="请选择试剂瓶类型"
										  :options="bottleTypeOptions" allowClear :disabled="!addFlag"/>
							</a-form-item>
						</a-col>

						<a-col :span="8">
							<a-form-item label="氧化还原类型：" name="reagentRedoxClassId"
										 :rules="[{ required: true, message: '请选择试氧化还原类型' }]">
								<a-select v-model:value="formData.reagentRedoxClassId" placeholder="请选择氧化还原类型"
										  :options="redoxClassOptions" allowClear :disabled="!addFlag"/>
							</a-form-item>
						</a-col>
						<a-col :span="16">
						</a-col>

						<a-col :span="8">
							<a-form-item label="购买者：" name="reagentBuyerName">
								<a-input v-model:value.trim="formData.reagentBuyerName"/>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="供应商：" name="reagentSupplier">
								<a-input v-model:value.trim="formData.reagentSupplier"/>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="购买凭证：" name="reagentPurchaseVoucher">
								<a-input v-model:value.trim="formData.reagentPurchaseVoucher"/>
							</a-form-item>
						</a-col>

						<a-col :span="24">
							<a-form-item label="备注：" name="remarks">
								<a-textarea v-model:value="formData.remarks" placeholder="请输入备注" allow-clear :rows="4"/>
							</a-form-item>
						</a-col>

						<a-col :span="24">
							<a-form-item label="所属柜子：" name="cabInfo">
								<a-row>
									<a-col :span="8">
										<a-select
											v-model:value="formData.bioCabinetGroupId"
											:options="cabinetGroupOptions"
											placeholder="请选择柜组"
											allow-clear
											@change="onChangeCabGropu"
											style="width: 300px"
										></a-select>
									</a-col>
									<a-col :span="8">
										<a-select
											v-model:value="formData.bioCabinetId"
											:options="cabinetOptions"
											placeholder="请选择柜子"
											allow-clear
											@change="onChangeCabInfo"
											style="width: 300px"
										></a-select>
									</a-col>
									<a-col :span="8">
										<a-select
											v-model:value="formData.bioCabinetDoorId"
											:options="cabinetDoorOptions"
											placeholder="请选择柜门"
											allow-clear
											style="width: 300px"
										></a-select>
									</a-col>
								</a-row>
							</a-form-item>
						</a-col>
					</a-row>
				</a-tab-pane>
				<a-tab-pane key="setting" tab="离柜设置">
					<a-collapse :activeKey="['1','2','3','4']">
						<a-collapse-panel key="1" header="离柜时间设置">
							<a-form-item label="最长离柜时限：" name="limitLeave">
								<a-space>
									<a-input-number v-model:value="formData.maxLimitLeave" placeholder="请输入最长离柜时限"
													:min="1" :max="100000" style="width: 300px"/>
									<a-select v-model:value="formData.maxLimitLeaveUnit" placeholder="请选择">
										<a-select-option value="1">分钟</a-select-option>
										<a-select-option value="2">小时</a-select-option>
										<a-select-option value="3">天</a-select-option>
									</a-select>
								</a-space>
							</a-form-item>
							<a-form-item label="到期前提示：" name="impend">
								<a-space>
									<a-input-number v-model:value="formData.impendPrompt" placeholder="请输入到期前提示"
													:min="1" :max="100000" style="width: 300px"/>
									<a-select v-model:value="formData.impendPromptUnit" placeholder="请选择">
										<a-select-option value="1">分钟</a-select-option>
										<a-select-option value="2">小时</a-select-option>
										<a-select-option value="3">天</a-select-option>
									</a-select>
								</a-space>
							</a-form-item>
							<a-form-item label="连续发送预警时间间隔：" name="alert">
								<a-space>
									<a-input-number v-model:value="formData.alertInterval" placeholder="请输入连续发送预警时间间隔"
													:min="1" :max="100000" style="width: 300px"/>
									<a-select v-model:value="formData.alertIntervalUnit" placeholder="请选择">
										<a-select-option value="1">分钟</a-select-option>
										<a-select-option value="2">小时</a-select-option>
										<a-select-option value="3">天</a-select-option>
									</a-select>
								</a-space>
							</a-form-item>
							<a-form-item label="连续发送预警最大次数：" name="alertMaxNum">
								<a-input-number v-model:value="formData.alertMaxNum" placeholder="请输入连续发送预警最大次数"
												:min="1" :max="100000" style="width: 300px"/>
							</a-form-item>
						</a-collapse-panel>
						<a-collapse-panel key="2" header="称重设置">
							<a-form-item label="取还是否需要称重：" name="reagentWeighNeedFlag"
										 :rules="[{ required: true, message: '请选择取还是否需要称重' }]">
								<a-select v-model:value="formData.reagentWeighNeedFlag" placeholder="请选择取还是否需要称重"
										  allowClear style="width: 300px">
									<a-select-option value="0">否</a-select-option>
									<a-select-option value="1">是</a-select-option>
								</a-select>
							</a-form-item>
							<a-form-item label="试剂重量误差最大值：" name="reagentMaxErrorValue"
										 :rules="[{ required: true, message: '请输入试剂重量误差最大值' }]">
								<a-input-number precision="2" v-model:value="formData.reagentMaxErrorValue"
												placeholder="请输入试剂重量误差最大值" allow-clear addon-after="g"
												style="width: 300px"/>
							</a-form-item>
						</a-collapse-panel>
						<a-collapse-panel key="3" header="借还设置">
							<a-form-item label="支持扫码入库、借还：" name="ssbrFlag">
								<a-switch v-model:checked="ssbrFlag" checked-children="是"
										  :disabled="!qrcodeFlag&&!barcodeFlag"
										  un-checked-children="否"/>
							</a-form-item>
						</a-collapse-panel>
						<a-collapse-panel key="4" header="借还检查项设置">
							<a-button type="primary" @click="checkItemRef.onOpen()" style="margin-bottom: 16px">
								<template #icon>
									<plus-outlined/>
								</template>
								新增检查项
							</a-button>
							<a-table :columns="checkColumns" :data-source="formData.checkItems" bordered
									 :pagination="false">
								<template #bodyCell="{ column, record ,index }">
									<template v-if="column.dataIndex === 'applScene'">
										<a-space size="1">
											<a-tag v-if="record.borrowCheck === 1" color="green">借用检查</a-tag>
											<a-tag v-if="record.returnInsp === 1" color="orange">归还检查</a-tag>
										</a-space>
									</template>
									<template v-if="column.dataIndex === 'state'">
										<a-switch
											:checked="record.state === 1"
											checked-children="启用" un-checked-children="停用"
											@change="switchCheckItem(record,index)"
										/>
									</template>
									<template v-if="column.dataIndex === 'action'">
										<a-space size="2">
											<a-tooltip title="编辑">
												<a-button type="link" @click="editCheckItem(record,index)">
													<form-outlined/>
												</a-button>
											</a-tooltip>
											<a-tooltip title="移除">
												<a-button type="link" danger @click="removeCheckItem(index)">
													<delete-outlined/>
												</a-button>
											</a-tooltip>
										</a-space>
									</template>
								</template>
							</a-table>
						</a-collapse-panel>
					</a-collapse>
				</a-tab-pane>
			</a-tabs>
		</a-form>

		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button style="margin-right: 8px" type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
			<a-button style="margin-right: 8px" type="primary" ghost @click="reagentClassModalRef.onOpen()"
					  v-if="addFlag">更新通用属性
			</a-button>
		</template>

		<CheckItem ref="checkItemRef" @onBack="afterCheckItem"/>
		<Reagent-Class-Modal ref="reagentClassModalRef" @chooseReagentClass="chooseReagentClass"/>

	</a-drawer>
</template>

<script setup name="bizReagentForm">
	import { cloneDeep } from 'lodash-es'
	import { required } from '@/utils/formRules'
	import bizGoodsApi from '@/api/biz/bizGoodsApi'
	import bizUserApi from "@/api/biz/bizUserApi";
	import tool from "@/utils/tool";
	import bizCabinetGroupReagentApi from '@/api/biz/bizCabinetGroupReagentApi'
	import bizCabinetInfoReagentApi from '@/api/biz/bizCabinetInfoReagentApi'
	import bizCabinetDoorReagentApi from '@/api/biz/bizCabinetDoorReagentApi'
	import CheckItem from './checkItem.vue'
	import XnEditor from '@/components/Editor/index.vue'
	import fileApi from '@/api/dev/fileApi'
	import sysConfig from '@/config'
	import ReagentClassModal from './reagentClassModal.vue'


	// 抽屉状态
	const visible = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	const checkItemRef = ref()
	const reagentClassModalRef = ref()
	// 表单数据
	const formData = ref({})
	const submitLoading = ref(false)
	const activeKey = ref('base')

	const rfidFlag = ref(false)
	const qrcodeFlag = ref(false)
	const barcodeFlag = ref(false)
	const addFlag = ref(false)
	const ssbrFlag = ref(false)
	//柜组
	const cabinetGroupOptions = ref([])
	//柜子
	const cabinetOptions = ref([])
	//柜门
	const cabinetDoorOptions = ref([])
	//检查项坐标
	const checkItemIndex = ref(-1);

	const checkColumns = [
		{
			title: '检查项',
			dataIndex: 'checkItem',
		},
		{
			title: '描述',
			dataIndex: 'checkDes',
		},
		{
			title: '适用场景',
			dataIndex: 'applScene',
			width: 200
		},
		{
			title: '状态',
			dataIndex: 'state',
			width: 100
		},
		{
			title: '操作',
			dataIndex: 'action',
			width: 100
		}
	]

	//类型
	let storageTypeOptions = tool.dictList('REAGENT_STORAGE_TYPE')
	//形态
	let formTypeOptions = tool.dictList('REAGENT_FORM_TYPE')
	//氧化还原
	let redoxClassOptions = tool.dictList('REAGENT_REDOX_TYPE')
	//试剂瓶类型
	let bottleTypeOptions = tool.dictList('REAGENT_BOTTLE_TYPE')

	// 打开抽屉
	const onOpen = (record, type) => {
		visible.value = true
		loadCabGroup()
		formData.value.maxLimitLeaveUnit = "1"
		formData.value.impendPromptUnit = "1"
		formData.value.alertIntervalUnit = "1"
		if (type === 'add') {
			addFlag.value = true
			loadClassData(record)
		}
		if (type === 'edit') {
			addFlag.value = false
			loadData(record)
		}
	}

	const loadClassData = (record) => {
		formData.value.goodsName = record.reagentName
		formData.value.bizReagentClassId = record.id
		formData.value.reagentCasNo = record.casNo
		formData.value.reagentClassId = record.classId
		formData.value.reagentFormId = record.formId
		formData.value.reagentDensity = record.density
		formData.value.reagentUnit = record.unit
		formData.value.reagentRedoxClassId = record.redoxClassId
		formData.value.reagentBottleType = record.bottleType
		formData.value.maxLimitLeaveUnit = "1"
		formData.value.maxLimitLeave = record.maxLimitLeave
		formData.value.reagentWeighNeedFlag = record.weighNeedFlag
		formData.value.reagentMaxErrorValue = record.maxErrorValue
	}

	const loadData = (record) => {
		bizGoodsApi.bizGoodsDetail({
			goodsId: record.id
		}).then((data) => {
			rfidFlag.value = data.rfidFlag === 1
			qrcodeFlag.value = data.qrcodeFlag === 1
			barcodeFlag.value = data.barcodeFlag === 1
			ssbrFlag.value = data.ssbrFlag === 1
			if (data.bioCabinetGroupId) {
				onChangeCabGropu(data.bioCabinetGroupId)
			}
			if (data.bioCabinetId) {
				onChangeCabInfo(data.bioCabinetId)
			}
			let recordData = cloneDeep(data)
			//处理几个单位
			if (data.maxLimitLeaveUnit) {
				recordData.maxLimitLeaveUnit = data.maxLimitLeaveUnit + ''
			} else {
				recordData.maxLimitLeaveUnit = "1"
			}
			if (data.impendPromptUnit) {
				recordData.impendPromptUnit = data.impendPromptUnit + ''
			} else {
				recordData.impendPromptUnit = "1"
			}
			if (data.alertIntervalUnit) {
				recordData.alertIntervalUnit = data.alertIntervalUnit + ''
			} else {
				recordData.alertIntervalUnit = "1"
			}
			if(!recordData.reagentValidityPeriod){
				delete recordData.reagentValidityPeriod
			}
			formData.value = Object.assign({}, recordData)
			if (data.unknownFlag === 1) {
				addFlag.value = true
			} else {
				addFlag.value = false
			}
		})
	}

	const chooseReagentClass = (data) => {
		loadClassData(data)
	}

	// 关闭抽屉
	const onClose = () => {
		formRef.value.resetFields()
		formData.value = {}
		visible.value = false
		rfidFlag.value = false
		qrcodeFlag.value = false
		barcodeFlag.value = false
		ssbrFlag.value = false
		cabinetOptions.value = []
		cabinetDoorOptions.value = []
		activeKey.value = 'base'
		checkItemIndex.value = -1
	}

	//加载柜组
	const loadCabGroup = () => {
		bizCabinetGroupReagentApi.bizCabinetGroupList({}).then((res) => {
			cabinetGroupOptions.value = res.map((item) => {
				return {
					label: `${item.cabinetGroupCode}-${item.cabinetGroupName}`,
					value: item.id
				}
			})
		})
	}

	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				submitLoading.value = true
				const formDataParam = cloneDeep(formData.value)
				formDataParam.rfidFlag = rfidFlag.value ? 1 : 0
				formDataParam.qrcodeFlag = qrcodeFlag.value ? 1 : 0
				formDataParam.barcodeFlag = barcodeFlag.value ? 1 : 0
				formDataParam.ssbrFlag = ssbrFlag.value ? 1 : 0;
				formDataParam.goodsType = 1
				bizGoodsApi
					.bizGoodsSubmitForm(formDataParam, !formDataParam.id)
					.then(() => {
						onClose()
						emit('successful')
					})
					.finally(() => {
						submitLoading.value = false
					})
			})
	}
	//柜组切换
	const onChangeCabGropu = (value) => {
		formData.value.bioCabinetId = undefined
		formData.value.bioCabinetDoorId = undefined
		cabinetOptions.value = []
		cabinetDoorOptions.value = []
		bizCabinetInfoReagentApi.bizCabinetList({ groupId: value }).then((res) => {
			cabinetOptions.value = res.map((item) => {
				return {
					label: `${item.cabinetName}`,
					value: item.id
				}
			})
		})

	}
	//柜子切换
	const onChangeCabInfo = (value) => {
		formData.value.bioCabinetDoorId = undefined
		cabinetDoorOptions.value = []
		bizCabinetDoorReagentApi.bizCabinetDoorList({ cabinetInfoId: value }).then((res) => {
			cabinetDoorOptions.value = res.map((item) => {
				return {
					label: `${item.cabinetDoorName}`,
					value: item.id
				}
			})
		})

	}
	// 检查项选择器回调
	const afterCheckItem = (data) => {
		console.warn("aaa=>", checkItemIndex.value)
		console.warn("bbbb=>", checkItemIndex.value ? 1 : 0)
		if (checkItemIndex.value >= 0) {
			formData.value.checkItems.splice(checkItemIndex.value, 1, data)
		} else {
			let checkItems = [];
			if (formData.value.checkItems) {
				formData.value.checkItems.map((item) => {
					checkItems.push(item);
				})
			}
			checkItems.push(data)
			formData.value.checkItems = checkItems
		}
		checkItemIndex.value = -1
	}
	// 移除检查项
	const removeCheckItem = (index) => {
		formData.value.checkItems.splice(index, 1)
	}
	// 切换检查项
	const switchCheckItem = (record, index) => {
		formData.value.checkItems[index].state = record.state === 1 ? 0 : 1
	}
	//编辑检查项
	const editCheckItem = (record, index) => {
		checkItemIndex.value = index;
		checkItemRef.value.onOpen(record)
	}

	// 抛出函数
	defineExpose({
		onOpen
	})
</script>
